/*
	@Author：TangYi

	Description:一个通用的Windows C语言的轻型网络框架
	风格说明：虽然这是一个Windows程序，但试用linux的命名风格.

*/

#include "vs_world.h"
#include "debug_log.h"
#include "stdio.h"

//此DEMO用于演示 GET 和 PUSH
vs_world_t* init_vs_world()
{
	vs_world_t* vs_world;
	vs_world = (vs_world_t*)malloc(sizeof(vs_world_t));
	dbg_assert(vs_world != NULL);

	vs_world->connection_list = list_create();
	dbg_assert(vs_world->connection_list != NULL);
	
	vs_world->world_stop = 0;

	vs_world->connection_list_lock_name = "vs_world_conneciton_list_lock";
	return vs_world;
}

void vs_world_add_connection(vs_world_t* vs_world, connection_t* con)
{
	dbg_print("new connection VS_WORLD");

	lock(vs_world->connection_list_lock_name);

	listnode_t* node = list_node_create(con);
	list_push_back(vs_world->connection_list,node);

	unlock(vs_world->connection_list_lock_name);
}

//当我再次检查这段代码时，发现把它给锁住了，很欣慰！！
void vs_world_delete_connection(vs_world_t* vs_world, connection_t* con)
{
	dbg_print("disconnesct VS_WORLD");
	lock(vs_world->connection_list_lock_name);

	//此种写法不利于保护数据结构的内部结构，但是，作为DEMO，这样写了
	listnode_t* p = vs_world->connection_list->head;
	while(p)
	{
		if(p->data == con)
			break;
		p = p->next;
	}

	if(p)
		list_node_delete(vs_world->connection_list,p,NULL);

	unlock(vs_world->connection_list_lock_name);
}

//此处必须考虑可能的死锁情况
unsigned long WINAPI vs_world_worker_thread(void* param)
{
	vs_world_t* vs_world = (vs_world_t*)param;
	dbg_print("vs_world_worker_thread Start");

	while(!vs_world->world_stop)
	{
		Sleep(30);
		lock(vs_world->connection_list_lock_name);
		
		listnode_t* p = vs_world->connection_list->head;
		while(p)
		{
			connection_t* con = (connection_t*)p->data;
			
			packet_t* packet = pop_back_connection_recv_packet(con);
			//简单的ECHO，把输入队列中的包放到输出队列
			while(packet)
			{
				display_packet_bytes(packet);
				push_front_connection_send_packet(con, packet);
				packet = pop_back_connection_recv_packet(con);
			}

			p = p->next;
		}

		unlock(vs_world->connection_list_lock_name);
		
	}

	return 0;
}